<template>
  <div class="container">
    <el-form ref="dataForm" :model="conModel" label-width="92px" size="mini" class="search_content">
      <el-row :gutter="24">
        <el-col :span="4" class="common_input">
          <el-form-item label="工艺图编号:">
            <el-input v-model="conModel.ChartNo" clearable placeholder="请输入工艺图编号" @keyup.enter.native="getList('search')" />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_input">
          <el-form-item label="工艺图名称:">
            <el-input v-model="conModel.ChartName" clearable placeholder="请输入工艺图名称" @keyup.enter.native="getList('search')" />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_picker">
          <el-form-item label="创建时间:">
            <el-date-picker
              v-model="conModel.StartTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              alue-format="yyyy-MM-dd HH:mm"
              placeholder="请选择开始时间"
              size="mini"
              class="search_common_picker"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1" class="common_query">
          <el-button size="mini" @click="getList('search')">
            <span>查询</span>
          </el-button>
        </el-col>
        <div class="common_right_btn common_query">
          <el-col :span="1">
            <el-button @click="addPopup"><span>新增</span></el-button>
          </el-col>
        </div>
      </el-row>
    </el-form>
    <div class="table_content">
      <el-table
        v-loading="listLoading"
        :data="list"
        fit
        style="width: 100%;"
        :stripe="true"
        >
        <el-table-column align="center" label="工艺图编号">
          <template slot-scope="scope">
            {{ scope.row.p.ChartNo }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="工艺图名称">
          <template slot-scope="scope">
            {{ scope.row.p.ChartName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            {{ scope.row.p.Remark }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.p.CreateTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="更新时间">
          <template slot-scope="scope">
            {{ scope.row.p.UpdateTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="{row}">
            <span class="common_operation common_operation_2" @click="UploadPopup(row)">上传工艺图</span>
            <span v-show="row.p.IsUpload === 1" class="common_operation common_operation_2" @click="chartPopup(row)">查看工艺图</span>
            <span class="common_operation" @click="editPopup(row)">编辑</span>
            <span class="common_operation" @click="deletePopup(row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" class="my_pagination" :total="total" :PageIndex.sync="Parameter.PageIndex" :PageSize.sync="Parameter.PageSize" @pagination="getList" />
    <el-dialog :title="popupTitle[popupTitleKey]" :visible.sync="dialogFormVisible" class="newel-dialog common_add_edit_popup_one">
      <div class="el-dialog__body">
        <el-form ref="dataForm" :rules="rules" :model="temp" class="demo-ruleForm common_popup" label-width="100px">
          <el-row :gutter="24">
            <el-col :span="14" :offset="4">
              <div class="grid-content bg-purple">
                <el-form-item label="工艺图编号:" prop="ChartNo">
                  <el-input v-model="temp.ChartNo" type="text" placeholder="请输入工艺图编号" />
                </el-form-item>
                <el-form-item label="工艺图名称:" prop="ChartName">
                  <el-input v-model="temp.ChartName" type="text" placeholder="请输入工艺图名称" />
                </el-form-item>
                <el-form-item label="备注:" prop="Remark">
                  <el-input v-model="temp.Remark" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <hr class="common_popup_border_bottom">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="add_edit_btn cancel" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button class="add_edit_btn determine" @click="AddProcessChartInfo()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 查看工艺图 -->
    <el-dialog
      title=""
      :visible.sync="dialogFormVisibleChart"
      class="chart_popup"
      :modal-append-to-body="false"
    >
      <div class="container">
        <el-button @click="fullScreen()" class="chart_process" style="background: #3491FA">
          {{ screenText }}
        </el-button>
        <el-button class="chart_process" @click="dialogFormVisibleChart = false" style="background: #F53F3F">
          关闭
        </el-button>
      </div>
      <div v-html="imgCodeUrl" class="img_chart"></div>
    </el-dialog>
    <!-- 上传工艺图 -->
    <el-dialog
      :visible.sync="dialogFormVisibleUpload"
      class="upload_popup"
      :modal-append-to-body="false"
    >
      <div slot="title" class="header-title">
        <el-upload
          class="upload-demo"
          ref="upload"
          action="/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-change='uploadChange'
          :file-list="fileList"
          :limit="1"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取svg文件</el-button>
        </el-upload>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-change='uploadChange2'
          :file-list="fileList2"
          :limit="1"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取json文件</el-button>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel" @click="dialogFormVisibleUpload = false">取消</el-button>
        <el-button class="delete" @click="submitUpload()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogFormVisibleDelete"
      class="common_delete_popup"
      :modal-append-to-body="false"
    >
      <div slot="title" class="header-title">
        <span class="title-name"><i class="el-icon-warning delete_icon" /></span>
        <span class="title-age">工艺图</span>
      </div>
      <span class="delete_tips">工艺图删除后，不可恢复，是否继续删除?</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel" @click="dialogFormVisibleDelete = false">取消</el-button>
        <el-button class="delete" @click="DeleteProcessChartInfo()">删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { GetProcessChartInfo, AddProcessChartInfo, DeleteProcessChartInfo, DownloadTpl, UploadTpl, GetDispText } from '@/api/basics'
import moment from 'moment'
import { getToken } from '@/utils/auth'
import axios from 'axios'

export default {
  name: 'ProcessChart',
  components: {
    Pagination
  },
  data() {
    return {
      Parameter: {
        PageSize: 10,
        PageIndex: 1,
        OrderBy: 'CreateTime',
        isDesc: true
      },
      conModel: {
        ChartNo: '',
        ChartName: '',
        StartTime: null
      },
      conModelCopy: {},
      temp: {
        ChartNo: '',
        ChartName: '',
        Remark: ''
      },
      searchkey: '', // 删除组件
      popupTitleKey: '',
      popupTitle: {
        add: '新增工艺图',
        edit: '编辑工艺图'
      },
      listLoading: false,
      dialogFormVisible: false,
      dialogFormVisibleDelete: false,
      dialogFormVisibleChart: false,
      dialogFormVisibleUpload: false,
      list: [],
      total: 0,
      rules: {
        ChartNo: [
          { required: true, message: '请输入工艺图编号', trigger: 'change' }
        ],
        ChartName: [
          { required: true, message: '请输入工艺图名称', trigger: 'change' }
        ]
      },
      imgCodeUrl: '',
      screenState: false,
      screenText: '全屏',
      fileList: [],
      fileList2: [], 
      timer: ''
    }
  },
  watch: {
    dialogFormVisibleChart() {
      if (this.dialogFormVisibleChart) {
        this.timer = setInterval(() => {
          GetDispText(this.temp.ChartNo).then(res => {
            if (res.State === 'success') {
              let list = res.Data
              this.$nextTick(() => {
                for (let i = 0; i < list.length; i++) {
                  // 先获取外层的id,再获取子id更改文本
                  let html = document.getElementById(list[i].Id).firstChild
                  let htmlId = html.getAttribute('id')
                  document.getElementById(htmlId).innerHTML = list[i].DispText
                }
              })
            }
          })
        }, 15000)
      } else {
        clearInterval(this.timer)
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 给文件赋值
    uploadChange(file, fileList){
      this.fileList = fileList
    },
    uploadChange2(file, fileList){
      this.fileList2 = fileList
    },
    submitUpload() {
      // 上传前，判断文件格式
      let formData = new FormData();
      if (this.fileList.length > 0 && this.fileList[0].raw.type === 'image/svg+xml') {
        formData.append('files',this.fileList[0].raw)
      } else {
        this.$message({
          message: '请选择一个svg格式的文件',
          type: 'error'
        })
        return
      }

      if (this.fileList2.length > 0 && this.fileList2[0].raw.type === 'application/json') {
        formData.append('files',this.fileList2[0].raw)
      } else {
        this.$message({
          message: '请选择一个json格式的文件',
          type: 'error'
        })
        return
      }
      UploadTpl(formData,this.temp.ChartNo).then(res => {
        if (res.State === 'success') {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          this.dialogFormVisibleUpload = false
        }
      })
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file)
    },
    // 上传文件弹窗
    UploadPopup(row) {
      this.dialogFormVisibleUpload = true
      this.fileList = []
      this.fileList2 = []
      this.temp.ChartNo = row.p.ChartNo
    },
    // 获取工艺图图片和配置文件
    chartPopup(row) {
      this.resetTemp()
      this.screenState = false
      this.screenText = '全屏'
      this.temp = Object.assign({}, row.p)
      if (this.temp.Width === 0) {
        this.temp.Width = '1080'
      }
      if (this.temp.Height === 0) {
        this.temp.Height = '780'
      }
      DownloadTpl(row.p.ChartNo).then(res => {
        this.imgCodeUrl = res
      })

      GetDispText(this.temp.ChartNo).then(res => {
        if (res.State === 'success') {
          this.dialogFormVisibleChart = true
          let dialog = document.getElementsByClassName("el-dialog")[2]
          dialog.style.cssText = "margin-top:3vhpx !important";
          dialog.style.width = this.temp.Width + 'px'
          dialog.style.height = this.temp.Height + 'px'
          let list = res.Data
          this.$nextTick(() => {
            for (let i = 0; i < list.length; i++) {
              // 先获取外层的id,再获取子id更改文本
              let html = document.getElementById(list[i].Id).firstChild
              let htmlId = html.getAttribute('id')
              document.getElementById(htmlId).innerHTML = list[i].DispText
            }
          })
        }
      })
    },
    getList(init) {
      if (init === 'search') {
        this.Parameter.PageIndex = 1
        this.conModelCopy = {}
      }
      if (this.conModel.ChartNo.trim() !== '' && init === 'search') {
        this.conModelCopy.searchkey = this.conModel.ChartNo.trim()
      }
      if (this.conModel.ChartName.trim() !== '' && init === 'search') {
        this.conModelCopy.Name = this.conModel.ChartName.trim()
      }
      if (this.conModel.StartTime !== null && init === 'search') {
        this.conModelCopy.StartTime = moment(this.conModel.StartTime).format('YYYY-MM-DD HH:mm')
      }
      this.listLoading = true
      var Parameter = {
        ...this.Parameter,
        ...this.conModelCopy
      }
      GetProcessChartInfo(Parameter).then(res => {
        this.list = res.Data
        this.total = res.Total
        this.listLoading = false
      })
    },
    addPopup() {
      this.popupTitleKey = 'add'
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    AddProcessChartInfo() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          AddProcessChartInfo(this.temp).then((res) => {
            if (res.State === 'success') {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getList()
              this.resetTemp()
            }
          })
        }
      })
    },
    editPopup(row) {
      this.popupTitleKey = 'edit'
      this.resetTemp()
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row.p)
    },
    deletePopup(row) {
      this.dialogFormVisibleDelete = true
      this.searchkey = row.p.ChartNo
    },
    DeleteProcessChartInfo() {
      DeleteProcessChartInfo({ searchkey: this.searchkey }).then((res) => {
        if (res.State === 'success') {
            this.$message({
              message: res.Result || '删除成功',
              type: 'success'
            })
            this.getList()
            this.dialogFormVisibleDelete = false
        }
      })
    },
    // 全屏
    fullScreen() {
      this.screenState = !this.screenState
      let dialog = document.getElementsByClassName("el-dialog")[2]
      if (this.screenState) {
        this.screenText = '退出全屏'
        dialog.style.cssText = "margin-top:0px !important";
        dialog.style.width = '100%'
        dialog.style.height = '100%'
      } else {
        this.screenText = '全屏'
        dialog.style.cssText = "margin-top:3vhpx !important";
        dialog.style.width = this.temp.Width + 'px'
        dialog.style.height = this.temp.Height + 'px'
      }
    },
    resetTemp() {
      this.temp = {
        ChartNo: '',
        ChartName: '',
        Remark: '',
        ExtData: '{}'
      }
    }
  }
}
</script>

<style>
.chart_popup .el-dialog{
  margin-top: 3vh !important;
  width: 1020px;
  height: 808px;
}

.chart_popup .el-dialog__body {
  padding: 0px;
}

.chart_popup .container {
  margin-left: 15px;
}

.chart_process {
  height: 30px;
  line-height: 0;
  color: #FFF !important;
}

.chart_process:hover {
  color: #FFF;
}

.upload_popup .el-dialog{
  width: 380px;
  height: 280px;
}

.upload_popup .el-dialog__header {
  padding-top: 50px;
  height: 30px;
}

.upload_popup .el-dialog__footer{
  position: absolute;
  right: 0px;
  bottom: 0px;
  padding: 16px;
}

.upload-demo {
  margin-bottom: 10px;
  width: 120px;
}

.upload-demo .el-button {
  width: 120px !important;
}

.el-upload-list {
  width: 200px;
}
</style>
